<?php
/**
 * Created by PhpStorm.
 * User: wangx08
 * Date: 2015-03-28
 * Time: 17:19
 */
namespace common\repositories\common;

use common\repositories\BaseRepository;
use common\entities\common\MyscrmOrganizationEntity;
use yii\helpers\ArrayHelper;
use common\support\PageParam;
use common\support\Helper;

class MyscrmOrganizationRepository extends BaseRepository {

    /**
     * 根据租户UniqueName(企业号)获取其ID
     * @param $orgName
     * @return string
     */
    public function getOrgId($orgName)
    {
        $org = $this->getOrgByUniqueName($orgName);
        if($org){
            return $org->Id;
        }
        return null;
    }

    /**
     * 根据租户UniqueName(企业号)获取详情
     * @param $orgName
     * @return null|MyscrmOrganizationEntity
     */
    private function getOrgByUniqueName($orgName)
    {
        return MyscrmOrganizationEntity::findOne([
            "UniqueName"=>$orgName
        ]);
    }


    /**
     * 分页获取租户列表
     * @param PageParam $pageParam
     * @param string $keyword 搜索关键字
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getOrganizationListByPage(PageParam $pageParam, $keyword){
        if (is_null($keyword) && empty($keyword)) {
            return [];
        }

        $query = MyscrmOrganizationEntity::find()
                ->select('Id, DatabaseName, InstanceName, InstanceId, UniqueName, FriendlyName, State, Email, UpgradeSerialNumber,
                        IsCanUpgrade, CreatedOn, ModifiedOn, VersionNumber, CustomManager, CustomManagerPhone, Deliver, DeliverPhone, ScheduleKey,
                        Area, LogoUrl')
                ->where(['like','FriendlyName',$keyword])
                ->orWhere(['like','UniqueName',$keyword]);



        $total = $query->count();
        $items = $query->orderBy([$pageParam->sortBy => $pageParam->sortAsc])
            ->offset($pageParam->getSkipByPageParam())
            ->limit($pageParam->pageSize)
            ->asArray()
            ->all();

        return Helper::setPageResult($total, $items);
    }

    /**
     * 根据ID获取租户信息对象
     * @param $organizationId
     * @return null|static
     */
    public static function getById($organizationId){
        return MyscrmOrganizationEntity::findOne([
           'Id' => $organizationId
        ]);
    }

    /**
     * 更新租户交付信息
     * @param $info
     * @return bool
     * @throws \Exception
     */
    public function updateOrganizationDeliverInfo($info){
        $org = $this->getOrgByUniqueName($info['orgname']);
        if(empty($org)){
            throw new \Exception("租户不存在");
        }
        $org['Area'] = ArrayHelper::getValue($info, 'area', '');
        $org['Deliver'] = ArrayHelper::getValue($info, 'deliver', '');
        $org['DeliverPhone'] = ArrayHelper::getValue($info, 'deliver_phone', '');
        $org['CustomManager'] = ArrayHelper::getValue($info, 'custom_manager', '');
        $org['CustomManagerPhone'] = ArrayHelper::getValue($info, 'custom_manager_phone', '');
        if($org->save()){
            return true;
        }else{
            throw $this->throwException($org->getFirstErrors());
        }
    }


    /**
     * 获取租户列表（select2控件）
     * @param string $keyword 搜索关键字
     * @param int $limit
     * @return array
     */
    public function getOrganizationListForSelect2($keyword,$limit = 10) {
        if (is_null($keyword) && empty($keyword)) {
            return [];
        }

        return MyscrmOrganizationEntity::find()
            ->select('Id as id,FriendlyName as text')
            ->where(['like','FriendlyName',$keyword])
            ->orWhere(['like','UniqueName',$keyword])
            ->orderBy(['FriendlyName' => SORT_ASC])
            ->limit($limit)
            ->asArray()
            ->all();
    }

}